<template>
	<div class="page flex-column">
		<van-nav-bar :title="`${editing ? '编辑' : '新增'}预约`" left-arrow @click-left="goBack" />
		<div class="page-body">
			<el-form ref="form" label-position="top" :model="form" :rules="rules">
				<el-form-item label="预约事业部" prop="biz_id">
					<cus-select
						:list="business"
						label="biz_name"
						prop="biz_id"
						v-model="form.biz_id"
						placeholder="请选择事业部"
						@change="changeBiz"
						:disabled="editing"
					/>
				</el-form-item>
				<el-form-item label="品牌" prop="bra_id">
					<cus-select
						v-model="form.bra_id"
						placeholder="请选择品牌"
						:list="bizRefData.brand"
						label="bra_name"
						prop="bra_id"
					/>
				</el-form-item>
				<el-form-item label="预约门店" prop="dept_id">
					<!-- <cus-select
						v-model="form.dept_id"
						placeholder="请选择预约门店"
						:list="shopList"
						label="dept_name"
						prop="dept_id"
					/> -->
					<choice-shop
						placeholder="请选择预约门店"
						:biz_id="form.biz_id"
						v-model="form.dept_id"
						only-open
						@confirm="confirmShop"
					/>
				</el-form-item>
				<el-form-item label="是否指定预约时间" prop="timeIsok">
					<cus-select
						filt
						:list="[
							{ label: '否', value: 0 },
							{ label: '是', value: 1 }
						]"
						label="label"
						prop="value"
						v-model="form.timeIsok"
						placeholder="请选择是否指定预约时间"
						@change="timeIsokChange"
					/>
				</el-form-item>
				<el-form-item label="预约时间" prop="appoint_date" v-if="form.timeIsok == 1">
					<cus-time
						:fixation="false"
						placeholder="请选择预约时间"
						v-model="form.appoint_date"
						:min-time="appointMinTime"
						value-format="YYYY-MM-DD HH:mm"
					/>
				</el-form-item>
				<el-form-item label="预约时长" prop="cart_duration">
					<cus-select
						filt
						:list="timeList"
						label="label"
						prop="value"
						v-model="form.cart_duration"
						placeholder="请选择是否指定预约时间"
					/>
				</el-form-item>

				<el-form-item label="预约内容" prop="serviceList">
					<template #label>
						<span>预约内容</span>
						<el-button type="text" style="float: right" @click="addService">
							{{ form.serviceList.length > 0 ? "修改服务" : "添加服务" }}
						</el-button>
					</template>
					<div class="reserv">
						<div
							class="reserv-item flex"
							v-for="(item, index) in form.serviceList"
							:key="index"
						>
							<div class="reserv-item__left flex">
								<div class="thumb">
									<!-- <img :src="item.picture_url" alt="" /> -->
									<cl-avatar :src="item.picture_url[0]" shape="square" />
								</div>
								<div class="name ellipsis">
									{{ item.si_name }}
								</div>
								<!-- <div class="name">￥{{ item.price }}</div> -->
								<div class="price flex">
									<span>￥</span>
									<input type="text" v-model="item.price" />
								</div>
							</div>
							<div class="reserv-item__right flex" @click="delService(index)">
								<i class="el-icon-error" />
							</div>
						</div>
					</div>
					<!-- <div class="add-serve flex" @click="addService">
						<i class="el-icon-plus" />
						<span>添加服务</span>
					</div> -->
				</el-form-item>
				<el-form-item label="预约备注" prop="remarks">
					<div class="item-con">
						<el-input
							v-model="form.remarks"
							placeholder="请填写预约备注"
							type="textarea"
							:rows="3"
						/>
					</div>
				</el-form-item>
			</el-form>
		</div>
		<div class="submit">
			<el-button type="primary" :loading="saving" @click="submit"> 提交 </el-button>
		</div>
		<reserv-pop
			:biz_id="form.biz_id"
			ref="reserv"
			@changeSelect="changeService"
			:items="form.serviceList"
		/>
	</div>
</template>
<script>
	import { NavBar } from "vant";
	import CusSelect from "./components/cus-select";
	import CusTime from "./components/cus-time";
	import ReservPop from "./components/reserv-pop";
	import dayjs from "dayjs";
	import { isArray } from "cl-admin/utils";
	import ChoiceShop from "./components/choice-shop";
	export default {
		name: "MobileCusAppoint",
		components: {
			VanNavBar: NavBar,
			CusSelect,
			CusTime,
			ReservPop,
			ChoiceShop
		},
		data() {
			return {
				brandList: [],
				form: {
					cart_id: undefined,
					biz_id: "", //事业部id
					bra_id: "",
					dept_id: "", //门店id
					// dept_ids: [],
					cus_id: "", //客户名
					cus_name: "", //客户名
					cus_mobile: "", //客户手机
					timeIsok: 0, //是否需要预约时间
					cart_duration: "",
					appoint_time: "",
					appoint_date: "", //预约日期
					appoint_btime: "", //预约开始时间
					serviceList: [], //已选服务列表
					remarks: "" //备注信息
					// region: "",
					// date1: "",
					// date2: "",
					// delivery: false,
					// type: [],
					// resource: "",
					// desc: ""
				},
				rules: {
					biz_id: [{ required: true, message: "请选择预约事业部" }],
					bra_id: [{ required: true, message: "请选择预约品牌" }],
					dept_id: [{ required: true, message: "请选择预约门店" }],
					cus_id: [{ required: true, message: "请选择会员姓名" }],
					appoint_date: [{ required: true, message: "请选择预约时间" }],
					cart_duration: [{ required: true, message: "请选择预约时长" }],
					serviceList: [
						{
							// type: "array",
							required: true,
							message: "请选择预约服务"
						}
					]
				},
				saving: false,
				editing: false,
				fromPage: ""
			};
		},

		computed: {
			bizRefData() {
				const { biz_id } = this.form;
				return this.getBizRefData(biz_id);
			},
			appointMinTime() {
				const { dept_id } = this.form;
				let res = this.bizRefData.shop_childs.find((v) => v.dept_id == dept_id);
				let now = dayjs();
				let btime = dayjs(now.format("YYYY-MM-DD") + " " + (res?.btime || "00:00"));
				if (btime.diff(now) > 0) {
					now = btime;
				}
				let minute = now.minute();
				let whole = now.set("m", 0).set("s", 0);
				let half = now.set("m", 30).set("s", 0);

				if (minute >= 0 && minute < 30) {
					return half.toDate();
				}
				if (minute >= 30 && minute < 59) {
					return whole.add(1, "h").toDate();
				}
				// if (!appoint_date) return new Date();
				// let appoint = dayjs(appoint_date);
				// if (appoint.isBefore(whole)) {
				// 	return now.toDate();
				// }
				// if (appoint.isBefore(half)) {
				// 	return half.toDate();
				// }
				return now.toDate();
			},
			timeList() {
				let hour = 4;
				let list = [];
				for (let i = 1; i <= hour * 2; i++) {
					list.push({ value: i * 30, label: i / 2 + "小时" });
				}
				return list;
			},
			appointMaxTime() {
				const { dept_id } = this.form;
				let res = this.bizRefData.shop_childs.find((v) => v.dept_id == dept_id);
				let now = dayjs();
				let etime = dayjs(now.format("YYYY-MM-DD") + " " + (res?.etime || "23:30"));
				if (etime.diff(now) > 0) {
					etime.toDate();
				}
				return now.toDate();
			}
		},
		created() {
			const { query } = this.$route;
			this.fromPage = query.from_page;
			this.init(query);
		},
		methods: {
			init(data = {}) {
				this.form.biz_id = this.getCurrBiz();
				this.editing = data.form_type == "edit";
				Object.keys(this.form).forEach((key) => {
					data[key] != undefined && (this.form[key] = data[key]);
				});

				if (data.dept_id == 0) {
					this.form.dept_id = "";
				}
				if (this.editing) {
					let timeIsok = data.appoint_date && data.appoint_date != "待定时间" ? 1 : 0;
					this.form.timeIsok = timeIsok;
					let service_info = JSON.parse(data.service_info);
					this.form.serviceList = service_info.map((v) => {
						return {
							...v,
							si_id: v.id,
							si_name: v.name,
							price: v.unit_price,
							picture_url: isArray(v.picture_url) ? v.picture_url[0] : v.picture_url
						};
					});
				} else {
					data.cus_type == 2 && this.getDefaultser(data);
				}
				this.$nextTick(() => {
					this.getBrandList();
				});
			},
			// 后退
			goBack() {
				this.$router.go(-1);
			},

			submit() {
				this.$refs.form.validate(async (valid, errors) => {
					this.showFormErr(errors);
					if (!valid) return;
					const { serviceList, dept_ids, appoint_date, timeIsok, ...args } = this.form;
					let isEmpty = serviceList.some((item) => item.price == "");
					if (isEmpty) {
						this.$message.warning("您有未补充服务信息");
						return;
					}
					let items = serviceList.map((v) => {
						return {
							type: 1,
							id: v.si_id,
							prod_id: v.si_id,
							name: v.si_name,
							lasttime: v.lasttime,
							picture_url: v.picture_url,
							product_category: v.product_category,
							unit_price: v.price,
							price: v.price,
							maintain_type: v.maintain_type || 0
						};
					});

					let form = {
						timeIsok,
						...args,
						appoint_btime: "",
						appoint_date: "",
						appoint_time: "",
						items: JSON.stringify(items),
						update_type: 1
					};
					if (timeIsok) {
						let appointTime = dayjs(appoint_date);
						form.appoint_time = appoint_date;
						form.appoint_btime = appointTime.format("HH:mm");
						form.appoint_date = appointTime.format("YYYY-MM-DD");
					}
					this.saving = true;
					await this.$service.cart[this.editing ? "update" : "add"](form).done(() => {
						this.saving = false;
					});
					this.$message.closeAll();
					this.$message.success(this.editing ? "修改成功" : "预约成功");
					if (this.fromPage !== "MobileCusDetail") {
						this.$router.replace({
							path: "/mobile/cus/detail",
							query: {
								biz_id:args.biz_id,
								cus_id: args.cus_id,
								cus_name: args.cus_name,
								cus_mobile: args.cus_mobile
							}
						});
						return;
					}
					this.goBack();
				});
			},
			// 更改预约事业部
			changeBiz() {
				this.form.dept_id = "";
				this.form.bra_id = "";
				this.getBrandList();
			},
			timeIsokChange(v) {
				if (v) return;
				this.form.appoint_date = "";
			},
			//获取默认服务
			async getDefaultser(row) {
				let { biz_id, cus_id } = row;
				let data = await this.$service.cart.getDefaultser({
					biz_id,
					cus_id
				});
				if (data.length) {
					this.form.serviceList.push({
						is_presents: 0,
						is_experience: 0,
						si_id: data[0].si_id,
						si_name: data[0].si_name,
						price: data[0].price
					});
				}
			},
			//添加服务
			addService() {
				this.$refs.reserv.open();
			},
			//删除服务
			delService(idx) {
				this.form.serviceList.splice(idx, 1);
			},
			// 服务
			changeService(list) {
				this.form.serviceList = list;
			},
			async getBrandList() {
				const { biz_id } = this.form;
				this.getBizRefBrand(biz_id);
			},
			confirmShop(val) {}
		}
	};
</script>
<style lang="scss" scoped>
	.page {
		height: 100vh;
		overflow: hidden;
		background: #fff;
		&-body {
			position: relative;
			flex: 1;
			overflow: auto;
			box-sizing: border-box;
			padding: 0.3rem 0 4rem;
			&::before {
				border-top: 1px solid #ebedf0;
				position: absolute;
				box-sizing: border-box;
				content: " ";
				pointer-events: none;
				top: -50%;
				right: -50%;
				bottom: -50%;
				left: -50%;
				transform: scale(0.5);
				z-index: 10;
			}
		}
	}
	::v-deep .el-form-item__label {
		width: 100%;
	}
	.item-con {
		align-items: center;
		padding-bottom: 0.1rem;
		border-bottom: 1px solid #dfdfdf;
		.icon {
			color: #999;
		}
	}
	.reserv {
		border-bottom: 1px solid #dfdfdf;
		margin-top: 0.1rem;
		.reserv-item {
			justify-content: space-between;
			border-top: 1px solid #dfdfdf;
			padding-bottom: 0.3rem;
			padding-top: 0.3rem;
			&__left {
				flex: 1;
				align-items: center;
				.thumb {
					width: 0.88rem;
					height: 0.88rem;
					margin-right: 0.3rem;
					img {
						width: 100%;
						height: 100%;
						object-fit: cover;
					}
				}
				.name {
					width: 40%;
					font-size: 0.28rem;
					font-weight: 400;
					color: #333;
					// &.mar-r {
					// 	margin-right: 0.99rem;
					// }
				}
				.price {
					border: 1px solid #dfdfdf;
					width: max-content;
					align-items: center;
					padding-left: 0.1rem;
					border-radius: 3px;
					overflow: hidden;
					span {
						font-size: 0.28rem;
						font-weight: 400;
						color: #999;
					}
					input {
						border: 0;
						width: 1.5rem;
					}
				}
			}
			&__right {
				align-items: center;
				i {
					font-size: 0.38rem;
					color: #dfdfdf;
				}
			}
		}
	}
	.add-serve {
		width: 3rem;
		height: 0.72rem;
		background: $primary;
		border-radius: 0.04rem;
		font-size: 0.24rem;
		color: #fff;
		justify-content: center;
		align-items: center;
		margin: 0 auto;
		span {
			font-weight: 400;
		}
		i {
			font-weight: bold;
			margin-right: 0.2rem;
		}
	}
	.submit {
		position: fixed;
		bottom: 0;
		width: 100%;
		box-sizing: border-box;
		padding: 0.2rem 0.3rem;
		background: #fff;
		box-shadow: 0 -0.04rem 0.1rem 0.01rem rgba(206, 206, 206, 0.2);
		.el-button {
			width: 100%;
			height: 0.7rem;
			font-size: 0.28rem;
		}
	}
</style>
